//
//  SWImageUploader.swift
//  ChildStory
//
//  Created by linhan on 16/8/22.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
class SWImageUploader: NSObject,SWAPIComponent
{
    override init()
    {
        super.init()
    }
    
    deinit
    {
        trace("DEINIT SWImageUploader")
    }
    
    func upload(image:UIImage, quality:CGFloat, successCallback:((String)->Void)?, failCallback:(()->Void)?)
    {
        guard let data = UIImageJPEGRepresentation(image, quality) else{
            return
        }
        
        upload(data: data, successCallback: successCallback, failCallback: failCallback)
    }
    
    func upload(data:Data, successCallback:((String)->Void)?, failCallback:(()->Void)?)
    {
        let time:Int = Int(NSDate().timeIntervalSince1970)
        let saveKey:String = "\(time)_\(StringUtil.getUniqid(5))"
        
        let req:SWUploadTokenFetchReq = SWUploadTokenFetchReq()
        req.successCallback = {[weak self] response, cache in
            if let response = response as? SWUploadTokenFetchRsp,
                let token = response.token, token != ""{
                trace("token:", token)
                
                //SW.Config.imageStoreBaseURL = response.baseURL ??? SW.Config.imageStoreBaseURL
                self?.QNUpload(data: data, saveKey: saveKey, uploadToken: token, successCallback: successCallback, failCallback: failCallback)
            }
            else
            {
                failCallback?()
            }
        }
        req.failCallback = {[weak self] error in
            failCallback?()
        }
        load(req)
    }
    
    static let QNUploadConfig:QNConfiguration = QNConfiguration.build { builder in
        QNAutoZone()
        builder?.setZone(QNAutoZone(https: true, dns: nil))
    }
    
    func QNUpload(data:Data, saveKey:String, uploadToken:String, successCallback:((String)->Void)?, failCallback:(()->Void)?)
    {
//        let config:QNConfiguration = QNConfiguration.build { builder in
//            builder?.setZone(QNAutoZone(https: true, dns: nil))
//        }
        let uploadManager:QNUploadManager = QNUploadManager(configuration: SWImageUploader.QNUploadConfig)
        uploadManager.put(data, key:saveKey, token:uploadToken, complete:{ info, akey, response in
            if let response = response,
               let key = response["key"] as? String, key != ""
            {
                let url:String = "\(SW.Config.imageStoreBaseURL)/\(key)"
                successCallback?(url)
                trace(url)
            }else{
                failCallback?()
            }
            }, option:nil)
    }
    
    
    
    
}
